<!--咨询师样式-->
<script setup>
import { ref, onMounted, reactive } from 'vue';
import request from "@/utils/request.js";
import { ElMessage } from "element-plus";

const params = reactive({
  pageNum: 1,
  pageSize: 10,
  name: ''
});
/*数据*/
const name = ref("");
const pageNum = ref(1);
const pageSize = ref(10);
const total = ref(0);
//等级
const consultantLevel1 = ref()
//存储等级信息
const consultantLevelList = ref()
//擅长领域
const expertises = ref([]);
//存储擅长领域信息
const expertiseList = ref([]);
//证书
const certificates = ref([]);
//存储证书信息
const certificateList = ref([]);
const tx = ref();
const consultant = ref({
  id: "",
  username: "",
  password: "",
  name: "",
  tel: "",
  gender: "",
  tx: "",
  area: "",
  levelId: "",
  qualification: "",
  introduction: "",
  isVerified: "",
});
/*批量删除数组数据*/
const multipleSelection = ref([]);
/*列表渲染数据*/
const tableData = ref([]);
const dialogFormVisible = ref(false);
const dialogTitle = ref("");
const imgURL = ref("");

const getTableData = async () => {
  try {
    const res = await request.get('/consultant/findConsultantByName', {
      params: {
        pageNum: pageNum.value,
        pageSize: pageSize.value,
        name: name.value
      }
    });
    if (res.code === 200) {
      tableData.value = res.data.list;
      console.log(tableData.value);
      total.value = res.data.total;
    }
  } catch (e) {
    ElMessage.error("列表渲染失败");
  }
};

/*重置按钮*/
const reset = () => {
  name.value = "";
  getTableData();
};
/*获取所有的证书信息*/
const getCertificates = async () => {
  try {
    const res = await request.get('/certificate/selectAll');
    if (res.code === 200) {
      certificateList.value = res.data;
    }
  } catch (e) {
    ElMessage.error("获取证书信息失败");
  }
};
/*获取所有的等级信息*/
const getConsultantLevel = async () => {
  try {
    const res = await request.get('/consultantLevel/findAll');
    if (res.code === 200) {
      consultantLevelList.value = res.data;
    }
  } catch (e) {
    ElMessage.error("获取等级信息失败");
  }
}
/*获取所有的擅长邻域信息*/
const getExpertises = async () => {
  try {
    const res = await request.get('/expertise/findAll');
    if (res.code === 200) {
      expertiseList.value = res.data;
    }
  } catch (e) {
    ElMessage.error("获取擅长邻域信息失败");
  }
}
/*新增*/
const add = () => {
  getCertificates();
  getConsultantLevel();
  getExpertises();
  consultant.value = {

  };
  consultantLevel1.value = "";
  expertises.value = [];
  certificates.value = [];
  dialogTitle.value = "新增";
  dialogFormVisible.value = true;
};

const addCharge = async () => {
  consultant.value = {
    ...consultant.value,
    tx: tx.value,
    levelId: consultantLevel1.value,
    expertiseIds: expertises.value,
    certificateIds: certificates.value,
  }
  try {
    const res = await request.post("/consultant/add", consultant.value);
    if (res.code === 200) {
      ElMessage.success("新增成功");
      getTableData();
    } else {
      ElMessage.error(res.msg);
      getTableData();
    }
  } catch (e) {
    ElMessage.error("新增失败");
    dialogFormVisible.value = false;
  }
};

/*更新*/
const handleEdit = (row) => {
  getCertificates();
  getConsultantLevel();
  getExpertises();
  consultant.value = row;
  consultantLevel1.value = row.consultantLevel.id;
  expertises.value = row.expertises.map(e => e.id);
  certificates.value = row.certificates.map(c => c.id);
  tx.value = row.tx;
  imgURL.value = `http://localhost:5173/api/files/${row.tx}`; // 根据你的实际路径拼接头像 URL
  dialogTitle.value = "更新";
  dialogFormVisible.value = true;
};

const updateCharge = async () => {
  consultant.value = {
    ...consultant.value,
    tx: tx.value,
    levelId: consultantLevel1.value,
    expertiseIds: expertises.value,
    certificateIds: certificates.value,
  }
  try {
    const res = await request.put("/consultant/update", consultant.value);
    if (res.code === 200) {
      ElMessage.success("更新成功");
      getTableData();
    } else {
      ElMessage.error(res.msg);
      getTableData();
    }
  } catch (e) {
    ElMessage.error("更新失败");
  }
};

/*弹出层提交事件*/
const submit = async () => {
  if (dialogTitle.value === "更新") {
    updateCharge();
  } else {
    addCharge();
  }
  dialogFormVisible.value = false;
};

/*弹出层取消事件*/
const cancel = () => {
  dialogFormVisible.value = false;
  getTableData();
};

/*删除*/
const handleDelete = async (row) => {
  const id = row.id;
  try {
    const res = await request.put(`/consultant/delete/${id}`);
    if (res.code === 200) {
      ElMessage.success("删除成功");
      getTableData();
    } else {
      ElMessage.error(res.msg);
    }
  } catch (e) {
    ElMessage.error("删除失败");
  }
};

/*批量删除*/
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};

const delBatch = async () => {
  try {
    const res = await request.put("/consultant/deleteBatch", multipleSelection.value);
    if (res.code === 200) {
      ElMessage.success("批量删除成功");
      getTableData();
    } else {
      ElMessage.error(res.msg);
    }
  } catch (e) {
    ElMessage.error("批量删除失败");
  }
};

/*批量导入*/
function successFileUpload(res) {
  if (res.code === 200) {
    ElMessage.success("批量导入成功");
    getTableData();
  }
}

//批量导出
function exp() {
  location.href = "http://localhost:5173/api/charge/export";
}

/*头像上传*/
const handleAvatarSuccess = (res, file) => {
  tx.value = res.data;
  if (res.code === 200) {
    imgURL.value = URL.createObjectURL(file.raw);
    ElMessage.success("头像上传成功");
    getTableData();
  } else {
    ElMessage.error(res.msg);
  }
};
const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}

/*分页*/
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  getTableData();
};

const handleCurrentChange = (newPage) => {
  pageNum.value = newPage;
  getTableData();
};

onMounted(() => {
  getTableData();
});
</script>

<template>
  <div>
    <!--  搜索框  -->
    <div class="btns">
      <el-input placeholder="请输入名称" style="width: 240px ; margin-right: 10px" v-model="name"></el-input>
      <el-button type="primary" @click="getTableData">搜索</el-button>
      <el-button type="warning" @click="reset">重置</el-button>
      <el-button type="success" @click="add">新增</el-button>
      <el-button type="danger" @click="delBatch">批量删除</el-button>
      <el-upload
        v-if="false"
        action="http://localhost:5173/api/charge/upload"
        :on-success="successFileUpload"
        :show-file-list="false"
        style="display: inline-block; margin: 0 10px"
      >
        <el-button type="primary">批量导入</el-button>
      </el-upload>
      <el-button v-if="false" type="success" @click="exp()">批量导出</el-button>
    </div>

    <!--  table表格  -->
    <div class="table-container">
      <el-table
        ref="multipleTableRef"
        size="large"
        :data="tableData"
        row-key="id"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" :selectable="selectable" />
        <el-table-column property="id" label="ID" width="75px" />
        <el-table-column property="name" label="名称" width="150px" />
        <el-table-column label="性别" width="75px">
          <template #default="scope">
            <div>{{ scope.row.gender == 0 ? "女" : "男" }}</div>
          </template>
        </el-table-column>
        <el-table-column property="consultantLevel.levelName" label="等级" width="150px" />
        <el-table-column label="头像" width="110px">
          <template #default="scope">
            <el-image
              style="width: 70px; height: 70px ; border-radius: 50% ; z-index: 10"
              :src="'http://localhost:5173/api/files/' + scope.row.tx"
              :preview-src-list="['http://localhost:5173/api/files/' + scope.row.tx]"
              preview-teleported
            />
          </template>
        </el-table-column>
        <el-table-column label="擅长邻域" min-width="200px">
          <template #default="scope">
            <div class="expertise-box">
              <div class="expertise" v-for="(item, index) in scope.row.expertises" :key="index">
                {{ item.expertiseName }}
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column property="area" label="地址" width="180px" />
        <el-table-column property="introduction" label="简介" min-width="250px">
          <template #default="scope">
            <div class="text-wrap">{{ scope.row.introduction }}</div>
          </template>
        </el-table-column>
        <el-table-column label="是否认证" width="120px">
          <template #default="scope">
            <div v-if="scope.row.isVerified == 1" style="color:blue">已认证</div>
            <div v-if="scope.row.isVerified == 0" style="color:red">未认证</div>
          </template>
        </el-table-column>
        <el-table-column property="levelName" label="证书" min-width="200px">
          <template #default="scope">
            <div class="expertise-box">
              <div class="expertise" v-for="(item, index) in scope.row.certificates" :key="index">
                {{ item.certificateName }}
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="165px">
          <template #default="scope">
            <el-button type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!--  弹出框  -->
    <el-dialog v-model="dialogFormVisible" :title="dialogTitle" width="500">
      <el-form :model="consultant">
        <el-form-item label="用户名:" :label-width="formLabelWidth">
          <el-input v-model="consultant.username" autocomplete="off" />
        </el-form-item>
        <el-form-item label="密码:" :label-width="formLabelWidth">
          <el-input v-model="consultant.password" autocomplete="off" />
        </el-form-item>
        <el-form-item label="名称:" :label-width="formLabelWidth">
          <el-input v-model="consultant.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="性别" :label-width="formLabelWidth">
          <el-radio-group v-model="consultant.gender">
            <el-radio :value="1">男</el-radio>
            <el-radio :value="0">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="等级" :label-width="formLabelWidth">
          <el-select
            placeholder="请选择等级"
            v-model="consultantLevel1"
            collapse-tags
            style="width: 240px"
          >
            <el-option
              v-for="item in consultantLevelList"
              :key="item.id"
              :label="item.levelName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="擅长" :label-width="formLabelWidth">
          <el-select
            placeholder="请选择子级擅长的邻域"
            v-model="expertises"
            collapse-tags
            multiple
            style="width: 240px"
          >
            <el-option
              v-for="item in expertiseList"
              :key="item.id"
              :label="item.expertiseName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="电话" :label-width="formLabelWidth">
          <el-input v-model="consultant.tel" autocomplete="off" />
        </el-form-item>
        <el-form-item label="地址" :label-width="formLabelWidth">
          <el-input v-model="consultant.area" autocomplete="off" />
        </el-form-item>
        <el-form-item label="简介" :label-width="formLabelWidth">
          <el-input v-model="consultant.introduction" autocomplete="off" />
        </el-form-item>
        <el-form-item label="认证" :label-width="formLabelWidth">
          <el-radio-group v-model="consultant.isVerified">
            <el-radio :value="0">未认证</el-radio>
            <el-radio :value="1">已认证</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="证书" :label-width="formLabelWidth">
          <el-select
            placeholder="请选择已获得的证书"
            v-model="certificates"
            collapse-tags
            multiple
            style="width: 240px"
          >
            <el-option
              v-for="item in certificateList"
              :key="item.id"
              :label="item.certificateName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="头像" :label-width="formLabelWidth">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:5173/api/files/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imgURL" :src="imgURL" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="submit">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!--  分页  -->
    <el-pagination
      v-model:current-page="params.pageNum"
      v-model:page-size="params.pageSize"
      :page-sizes="[5, 10, 15, 20]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<style scoped>
.btns {
  margin-bottom: 10px;
}

.table-container {
  width: 100%;
  overflow-x: auto;
}

.expertise {
  display: inline-block;
  margin: 5px;
  padding: 5px 10px;
  background-color: #d0d3d3;
  border-radius: 5px;
  white-space: normal;
  color: #4b5e8c;
}

.text-wrap {
  white-space: normal;
  word-break: break-all;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
